package gitee.cheungming.modules.dmp.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import gitee.cheungming.common.service.impl.CrudServiceImpl;
import gitee.cheungming.common.utils.ConvertUtils;
import gitee.cheungming.modules.dmp.dao.ClientDao;
import gitee.cheungming.modules.dmp.dto.ClientDTO;
import gitee.cheungming.modules.dmp.entity.ClientEntity;
import gitee.cheungming.modules.dmp.service.ClientService;
import gitee.cheungming.modules.security.user.SecurityUser;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * 客户端
 *
 * @author cheungming cheungming@gmail.com
 * @since 1.0.0 2025-08-21
 */
@Service
public class ClientServiceImpl extends CrudServiceImpl<ClientDao, ClientEntity, ClientDTO> implements ClientService {

    @Override
    public QueryWrapper<ClientEntity> getWrapper(Map<String, Object> params) {
        String id = (String) params.get("id");

        String clientName = (String) params.get("clientName");

        QueryWrapper<ClientEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(id), "id", id);
        wrapper.like(StrUtil.isNotBlank(clientName), "client_name", clientName);

        return wrapper;
    }


    @Override
    public void save(ClientDTO dto) {
        ClientEntity clientEntity = ConvertUtils.sourceToTarget(dto, ClientEntity.class);
        clientEntity.setClientKey(RandomUtil.randomString(32));
        clientEntity.setClientSecret(RandomUtil.randomString(64));
        clientEntity.setCreator(SecurityUser.getUserId());
        clientEntity.setCreateDate(new Date());
        insert(clientEntity);
    }

    @Override
    public void update(ClientDTO dto) {
        ClientEntity clientEntity = ConvertUtils.sourceToTarget(dto, ClientEntity.class);
        clientEntity.setUpdater(SecurityUser.getUserId());
        clientEntity.setUpdateDate(new Date());
        updateById(clientEntity);
    }
}